<template>
    <view class="container">
        <image class="bg-image" src="/static/image.jpg" mode="aspectFill"></image>
        
        <!-- 导航栏 -->
        <view class="nav-bar">
            <view class="back-btn" @click="goBack">
                <image src="/static/return.png" mode="aspectFit" class="back-icon"/>
            </view>
            <text class="nav-title">{{ learningType }}</text>
            <text class="remaining" v-if="remaining">
                剩余：{{ targetUnit === 'minutes' ? remaining : `${remaining}${targetUnit}` }}
            </text>
            <text class="remaining" v-else>&nbsp;</text>
        </view>

        <!-- 单词卡片 -->
        <view class="word-card">
            <view class="word-header">
                <text class="word-text">{{ currentWord.word_name }}</text>
                <view class="collect-btn" @click="showWordbookList">
                    <image src="/static/collect.jpg" mode="aspectFit" class="collect-icon"/>
                </view>
            </view>
            
            <!-- 发音部分 -->
            <view class="pronounce-section">
                <text class="soundmark">{{ currentWord.word_soundmark }}</text>
                <view class="sound-btn" @click="playPronunciation">
                    <image src="/static/me.png" mode="aspectFit" class="sound-icon"/>
                </view>
            </view>

            <!-- 释义 -->
            <view class="meaning-section">
                <text class="meaning-text">{{ currentWord.word_paraphrase }}</text>
            </view>
        </view>

        <!-- 按钮组 -->
        <view class="button-group">
            <button class="action-btn mastered" @click="handleMastered">已掌握</button>
            <button class="action-btn next" @click="handleNext">下一个</button>
        </view>

        <!-- 添加单词本选择弹窗 -->
        <view class="wordbook-popup" v-if="showPopup">
            <view class="popup-mask" @click="hideWordbookList"></view>
            <view class="popup-content">
                <view class="popup-header">
                    <text class="popup-title">选择单词本</text>
                    <view class="close-btn" @click="hideWordbookList">×</view>
                </view>
                <view class="wordbook-list">
                    <view 
                        class="wordbook-item" 
                        v-for="book in wordbooks" 
                        :key="book.wordbook_id"
                        @click="collectWord(book.wordbook_id)"
                    >
                        <text class="wordbook-name">{{ book.wordbook_name }}</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { next_word, is_get, user_wordbooks, add_word_to_wordbook } from '@/api/user.js'

export default {
    data() {
        return {
            currentWord: {},
            remaining: 0,
            learningType: '',
            targetUnit: '',
            audioContext: null,
            wordbooks: [],
            showPopup: false,
            initialRemaining: null,
            timer: null,
            timeRemaining: 0
        }
    },
    onLoad() {
        this.audioContext = uni.createInnerAudioContext()
        const lastRemaining = uni.getStorageSync('lastRemaining')
        if (lastRemaining) {
            this.initialRemaining = lastRemaining
        }
        this.loadNextWord()
    },
    computed: {
        formattedTimeRemaining() {
            if (this.targetUnit !== 'minutes') return ''
            
            const hours = Math.floor(this.timeRemaining / 3600)
            const minutes = Math.floor((this.timeRemaining % 3600) / 60)
            const seconds = this.timeRemaining % 60
            
            return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
        }
    },
    methods: {
        async loadNextWord() {
            try {
                const dictionary = uni.getStorageSync('currentDictionary')
                console.log('获取到的词典信息：', dictionary)
                
                if (!dictionary || !dictionary.plan_id) {
                    console.error('未找到词典信息')
                    uni.showToast({
                        title: '未找到学习计划',
                        icon: 'none'
                    })
                    return
                }

                const res = await next_word(dictionary.plan_id)
                
                console.log('获取单词响应：', res)
                if (res.code === 200) {
                    if (res.target_unit === 'minutes' && this.timeRemaining <= 0) {
                        this.timeRemaining = res.remaining * 60
                        this.startTimer()
                    }
                    
                    this.updateWordData(res)
                    
                    if (this.initialRemaining === null) {
                        this.initialRemaining = res.remaining
                        uni.setStorageSync('lastRemaining', res.remaining)
                        console.log('记录初始 remaining:', this.initialRemaining)
                        
                        if (res.target_unit === 'minutes') {
                            this.timeRemaining = res.remaining * 60
                            this.startTimer()
                        }
                    }
                } else {
                    console.error('接口返回错误：', res)
                    uni.showToast({
                        title: res.message || '获取单词失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('获取单词失败：', error)
                uni.showToast({
                    title: '获取单词失败，请重试',
                    icon: 'none'
                })
            }
        },

        shouldShowCompletionDialog(res) {
            if (this.initialRemaining === null) {
                return false
            }

            if (res.target_unit === 'minutes') {
                return this.timeRemaining <= 0
            } else {
                return res.remaining > this.remaining && this.remaining > 0
            }
        },

        updateWordData(res) {
            this.currentWord = res.word
            this.learningType = res.learning_type
            this.targetUnit = res.target_unit
            
            if (this.targetUnit === 'minutes') {
                this.remaining = this.formattedTimeRemaining
            } else {
                this.remaining = res.remaining || ''
            }
        },

        startTimer() {
            this.stopTimer()
            this.timer = setInterval(() => {
                if (this.timeRemaining > 0) {
                    this.timeRemaining--
                    if (this.targetUnit === 'minutes') {
                        this.remaining = this.formattedTimeRemaining
                    }
                } else {
                    this.stopTimer()
                    uni.showModal({
                        title: '计划完成',
                        content: '您已完成今日学习计划，是否继续学习？',
                        confirmText: '继续学习',
                        cancelText: '返回首页',
                        success: (result) => {
                            if (result.confirm) {
                                this.loadNextWord()
                            } else {
                                uni.navigateBack()
                            }
                        }
                    })
                }
            }, 1000)
        },

        stopTimer() {
            if (this.timer) {
                clearInterval(this.timer)
                this.timer = null
            }
        },

        playPronunciation() {
            if (this.currentWord.word_pronounce) {
                this.audioContext.src = this.currentWord.word_pronounce
                this.audioContext.play()
            }
        },
        async handleMastered() {
            try {
                if (!this.currentWord || !this.currentWord.word_id) {
                    console.error('未找到当前单词ID')
                    return
                }

                const res = await is_get(this.currentWord.word_id)
                console.log('标记已掌握响应：', res)

                if (res.code === '2000') {
                    uni.showToast({
                        title: '已标记为掌握',
                        icon: 'success'
                    })
                    this.loadNextWord()
                } else {
                    uni.showToast({
                        title: res.message || '操作失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('标记已掌握失败:', error)
                uni.showToast({
                    title: '操作失败，请重试',
                    icon: 'none'
                })
            }
        },
        handleNext() {
            if (this.targetUnit !== 'minutes' && this.remaining === 1) {
                uni.showModal({
                    title: '计划完成',
                    content: '您已完成今日学习计划，是否继续学习？',
                    confirmText: '继续学习',
                    cancelText: '返回首页',
                    success: (result) => {
                        if (result.confirm) {
                            this.loadNextWord()
                        } else {
                            uni.navigateBack()
                        }
                    }
                })
            } else {
                this.loadNextWord()
            }
        },
        goBack() {
            this.initialRemaining = null
            uni.removeStorageSync('lastRemaining')
            uni.navigateBack()
        },
        async showWordbookList() {
            try {
                const userId = this.getUserIdFromToken()
                console.log('获取到的用户ID:', userId)
                
                if (!userId) {
                    console.warn('未获取到用户ID')
                    uni.showToast({
                        title: '请先登录',
                        icon: 'none'
                    })
                    return
                }

                const res = await user_wordbooks({
                    user_id: String(userId)
                })
                
                console.log('获取单词本响应：', res)
                if (res.code === '2000') {
                    this.wordbooks = res.data
                    this.showPopup = true
                } else {
                    uni.showToast({
                        title: res.message || '获取单词本失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('获取单词本失败：', error)
                uni.showToast({
                    title: '获取单词本失败',
                    icon: 'none'
                })
            }
        },
        hideWordbookList() {
            this.showPopup = false
        },
        async collectWord(wordbookId) {
            try {
                const userId = uni.getStorageSync('user_id')
                if (!userId || !this.currentWord.word_id || !wordbookId) {
                    uni.showToast({
                        title: '参数不完整',
                        icon: 'none'
                    })
                    return
                }

                const res = await add_word_to_wordbook({
                    user_id: String(userId),
                    word_id: String(this.currentWord.word_id),
                    wordbook_id: String(wordbookId)
                })

                if (res.code === '2000') {
                    uni.showToast({
                        title: '收藏成功',
                        icon: 'success'
                    })
                    this.hideWordbookList()
                } else {
                    uni.showToast({
                        title: res.message || '收藏失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('收藏单词失败:', error)
                uni.showToast({
                    title: '收藏失败，请重试',
                    icon: 'none'
                })
            }
        },
        getUserIdFromToken() {
            const authorization = uni.getStorageSync('token')
            console.log('原始token:', authorization)
            
            if (!authorization) {
                console.warn('未找到token')
                return null
            }
            
            try {
                const token = authorization.replace('Bearer ', '')
                console.log('处理后的token:', token)
                
                const tokenParts = token.split('.')
                console.log('token分割结果:', tokenParts)
                
                if (tokenParts.length > 0) {
                    const userInfo = JSON.parse(tokenParts[0])
                    console.log('解析出的用户信息:', userInfo)
                    return userInfo.id
                }
                console.warn('token格式不正确')
                return null
            } catch (error) {
                console.error('解析token失败:', error)
                return null
            }
        }
    },
    onUnload() {
        this.initialRemaining = null
        uni.removeStorageSync('lastRemaining')
        this.stopTimer()
        if (this.audioContext) {
            this.audioContext.destroy()
        }
    }
}
</script>

<style>
.container {
    width: 100%;
    min-height: 100vh;
    position: relative;
}

.bg-image {
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    z-index: 1;
}

.nav-bar {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;
    padding: 40px 20px 20px;
}

.back-icon {
    width: 24px;
    height: 24px;
}

.nav-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    color: #333;
}

.remaining {
    font-size: 14px;
    color: #666;
}

.word-card {
    position: relative;
    z-index: 2;
    margin: 20px;
    padding: 30px;
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    border-radius: 16px;
}

.word-section {
    text-align: center;
    margin-bottom: 30px;
}

.word-text {
    font-size: 32px;
    color: #333;
    font-weight: 500;
    margin-bottom: 10px;
}

.pronounce-section {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.soundmark {
    font-size: 16px;
    color: #666;
}

.sound-btn {
    padding: 8px;
}

.sound-icon {
    width: 24px;
    height: 24px;
}

.meaning-section {
    padding: 20px 0;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.meaning-text {
    font-size: 16px;
    color: #333;
    line-height: 1.6;
}

.button-group {
    position: fixed;
    bottom: 40px;
    left: 20px;
    right: 20px;
    display: flex;
    gap: 20px;
    z-index: 2;
}

.action-btn {
    flex: 1;
    height: 44px;
    line-height: 44px;
    text-align: center;
    border-radius: 22px;
    font-size: 16px;
    border: none;
}

.mastered {
    background: rgba(107, 75, 138, 0.9);
    color: white;
}

.next {
    background: rgba(255, 255, 255, 0.9);
    color: #333;
}

.action-btn:active {
    opacity: 0.8;
}

.word-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.collect-btn {
    padding: 8px;
}

.collect-icon {
    width: 24px;
    height: 24px;
}

.wordbook-popup {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 999;
}

.popup-mask {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
}

.popup-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: white;
    border-radius: 16px 16px 0 0;
    padding: 20px;
    transform: translateY(0);
    transition: transform 0.3s ease;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.popup-title {
    font-size: 18px;
    font-weight: 500;
}

.close-btn {
    font-size: 24px;
    color: #999;
    padding: 5px;
}

.wordbook-list {
    max-height: 400px;
    overflow-y: auto;
}

.wordbook-item {
    padding: 15px;
    border-bottom: 1px solid #eee;
}

.wordbook-name {
    font-size: 16px;
    color: #333;
}
</style>
